<script setup>
import { queryGoodsDetail } from '@/api/goods'
import { getCurrentInstance, onMounted } from 'vue'
import { useCartStore } from '@/stores/cart'
const { proxy } = getCurrentInstance()
const route = useRoute()
const goodsDetail = ref(null)
onMounted(async () => {
  //根据路径参数中的ID调用接口返回商品的详情
  goodsDetail.value = await queryGoodsDetail(route.params.id)
})
//获取购物车仓库
const cartStore = useCartStore()
//在购物车列表里查找有没有此商品
function findCartItem(goodsId) {
  return cartStore.cartItems.find((item) => item.goodsId === goodsId)
}
//把当前的商品添加到购物车里面
const addCart = () => {
  const cartItem = findCartItem(Number(route.params.id))
  //如果此商品在购物里已经存在
  if (cartItem) {
    //限制每个商品每位顾客只能购买五个
    if (cartItem.goodsCount >= 5) {
      return proxy.$showFailToast('每个商品最多只能购物5个')
    } else {
      //更新购物车中商品的数量
      cartStore.updateCartList(cartItem.cartItemId, cartItem.goodsCount + 1)
    }
  } else {
    //向购物车仓库中添加一个新的商品
    cartStore.addCartList(route.params.id)
  }
  proxy.$showSuccessToast('添加成功')
}
</script>
<template>
  <NavBar title="商品详情"></NavBar>
  <van-skeleton :row="8" :loading="!goodsDetail">
    <div class="product-wrapper">
      <div class="product-info">
        <van-image :src="goodsDetail.goodsCoverImg"></van-image>
        <div class="product-desc">
          <h3 class="name">{{ goodsDetail.goodsName }}</h3>
          <p class="intro">{{ goodsDetail.goodsIntro }}</p>
          <p class="price">¥{{ goodsDetail.sellingPrice }}</p>
        </div>
        <div class="tabs">
          <a>概述</a>
          <span>|</span>
          <a>参数</a>
          <span>|</span>
          <a>安装服务</a>
          <span>|</span>
          <a>常见问题</a>
        </div>
        <div class="content" v-html="goodsDetail.goodsDetailContent"></div>
      </div>
    </div>
  </van-skeleton>
  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" />
    <van-action-bar-icon 
    icon="cart-o" 
    text="购物车" 
    @click="$router.push('/cart')" 
    :badge="cartStore.totalAmount"
    />
    <van-action-bar-button
      type="warning"
      text="加入购物车"
      @click="addCart"
    ></van-action-bar-button>
    <van-action-bar-button type="danger" text="立刻购买"></van-action-bar-button>
  </van-action-bar>
</template>
<style lang="less">
.product-wrapper {
  padding: 50px 10px;
  .product-info {
    padding: 0 10px;
    .product-desc {
      .name {
        font-size: 18px;
        color: #555;
        font-weight: normal;
      }
      .intro {
        padding: 10px 0;
        font-size: 14px;
        color: #999;
      }
      .price {
        font-size: 18px;
        color: #f63515;
      }
    }
    .tabs {
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      padding: 15px 0;
      a,
      span {
        font-size: 15px;
        color: #555;
      }
    }
    .content{
      img{
        width:100%;
      }
    }
  }
}
</style>
